package com.difsonapps.android.marker.fragments;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Cache;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.difsonapps.android.marker.AppConstant;
import com.difsonapps.android.marker.CustomRequest;
import com.difsonapps.android.marker.IRefresher;
import com.difsonapps.android.marker.ImageUploader;
import com.difsonapps.android.marker.MainActivity;
import com.difsonapps.android.marker.R;
import com.difsonapps.android.marker.UploadRequest;
import com.difsonapps.android.marker.R.layout;
import com.difsonapps.android.marker.activities.AlbumsActivity;
import com.difsonapps.android.marker.activities.LoginActivity;
import com.difsonapps.android.marker.activities.PhotoViewActivity;
import com.difsonapps.android.marker.adapters.AlbumGridAdapter;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.Album;
import com.difsonapps.android.marker.beans.User;
import com.difsonapps.android.marker.upload.HttpUploader;
import com.difsonapps.android.marker.util.MarkerUtil;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class EditProfileFragment extends Fragment {
    private static final String TAG = EditProfileFragment.class.getSimpleName();
	private final int SELECT_NEW_PHOTO_PROFILE = 100;
    //View loadingLayout;
	View formScrollView;
	
	ProgressDialog loadingProgressDialog;
	//TextView loadingStatusMessage;
	//TextView messageTextView;
	
	NetworkImageView profileImageView;
	ImageLoader imageLoader = AppController.getInstance().getImageLoader();
	ImageView selectedImageView;
	
	Button saveButton;
	Button chooseButton;
	
	EditText firstnameEditText;
	EditText lastnameEditText;
	EditText middlenameEditText;
	EditText occupationEditText;
	EditText aboutmeEditText;
	String currentUploadeFile = null;
	
	File currentSelectedFile=null;

	
	public EditProfileFragment(){}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
 
        View rootView = inflater.inflate(R.layout.fragment_edit_profile, container, false);

        //loadingLayout = rootView.findViewById(R.id.loading_status);
		formScrollView = rootView.findViewById(R.id.formScrollView);
		profileImageView = (NetworkImageView)rootView.findViewById(R.id.profileImageView);
		selectedImageView = (ImageView)rootView.findViewById(R.id.selectedImageView);
		
		//loadingStatusMessage = (TextView) rootView.findViewById(R.id.loading_status_message);
		//messageTextView = (TextView) rootView.findViewById(R.id.messageTextView);
		
		firstnameEditText = (EditText) rootView.findViewById(R.id.firstnameEditText);
		lastnameEditText = (EditText) rootView.findViewById(R.id.lastnameEditText);
		middlenameEditText = (EditText) rootView.findViewById(R.id.middlenameEditText);
		occupationEditText = (EditText) rootView.findViewById(R.id.occupationEditText);
		aboutmeEditText = (EditText) rootView.findViewById(R.id.aboutmeEditText);
		
		chooseButton = (Button)rootView.findViewById(R.id.chooseButton);
		saveButton = (Button)rootView.findViewById(R.id.saveButton);
		saveButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				save();
			}
		});
		
		chooseButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {				
				Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
				photoPickerIntent.setType("image/*");
				startActivityForResult(photoPickerIntent, SELECT_NEW_PHOTO_PROFILE);
			}
		});
		
		load();
         
        return rootView;
    }
	
	 @Override
	    public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
	        super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
	 
	        switch(requestCode) { 
	        case SELECT_NEW_PHOTO_PROFILE:
	            if(resultCode == Activity.RESULT_OK){
					try {
						toast("Answered!");
						//showProgress();
						final Uri imageUri = imageReturnedIntent.getData();
						toast(imageUri.getPath());
						toast(getPath(imageUri));
						File file = new File(getPath(imageUri));
						if(file.exists()) currentSelectedFile = file;
						final InputStream imageStream = getActivity().getContentResolver().openInputStream(imageUri);
						final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
						selectedImageView.setImageBitmap(selectedImage);
						selectedImageView.setVisibility(View.VISIBLE);
						profileImageView.setVisibility(View.GONE);
						//hideProgress();
						upload();
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
	 
	            }
	        }
	    }
	 
	 public String getPath(Uri uri) {
	    	String[] projection = { MediaStore.Images.Media.DATA };
	    	Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
	    	getActivity().startManagingCursor(cursor);
	    	int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    	cursor.moveToFirst();
	    	return cursor.getString(column_index);
	    }
	
	public void load(){
		showProgress();
		getCurrentUser();
    }
	
	private void showPhotosFragment(Album album){
		((MainActivity)getActivity()).showPhotosFragment(album);
	}
	
	private void showProgress(){
		loadingProgressDialog = ProgressDialog.show(getActivity(), getResources().getString(R.string.loading), getResources().getString(R.string.loading), true);
        loadingProgressDialog.setCancelable(true);
		//loadingLayout.setVisibility(View.VISIBLE);
	}
	
	private void hideProgress(){
		if(loadingProgressDialog!=null) loadingProgressDialog.dismiss();
		//loadingLayout.setVisibility(View.GONE);
	}
	
	private void save(){
		String firstname = firstnameEditText.getText().toString().trim();
		String lastname = lastnameEditText.getText().toString().trim();
		String middlename = middlenameEditText.getText().toString().trim();
		String occupation = occupationEditText.getText().toString().trim();
		String aboutme = aboutmeEditText.getText().toString().trim();
		if(firstname.equals("") || lastname.equals("")){
			toast(getResources().getString(R.string.type_firstname));
			return;
		}
		Map<String, String> params = new HashMap<String, String>();
        params.put("firstname", firstname);//TODO Put the id of the image selected here
        params.put("lastname", lastname);
        params.put("middlename", middlename);
        params.put("occupation", occupation);
        params.put("aboutme", aboutme);
        if(currentUploadeFile!=null && !"".equals(currentUploadeFile.trim())) {
        	params.put("image", currentUploadeFile);
        	toast("Image : "+currentUploadeFile);
        }
		showProgress();
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				AppConstant.editaccountUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	hideProgress();
                    	toast("Response : "+response.toString());
                    	Log.i("Test", response.toString());
                    	parseJsonSave(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	hideProgress();
                    	toast("Error: " + error.getMessage());
                    	Log.e("Test", error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	private void parseJsonSave(JSONObject response){
		try {
			if(response.has("result_code")){
				String resultCode = response.getString("result_code");
				if(resultCode.equals("success")){
					String success = response.getString("success");					
					toast(success);
					User user = User.parseFromJsonObject(response);
					if(user!=null){
						AppConstant.userConnected = user;
						if(getActivity() instanceof MainActivity) ((MainActivity)getActivity()).reloadUser();
						//TODO update the main activity to show the new informations
					}
					//TODO update view and infos in userconnected
				}else if(response.has("error")){
	            	String error = response.getString("error");
	            	//TODO Show the error message in a textView and make it visible
	            	//loginErrorView.setText(error);
	            	//loginErrorView.setVisibility(View.VISIBLE);
	            	toast(error);
	            }else if(response.has("exception")){
	            	String error = response.getString("error");
	            	//TODO Show the error message in a textView and make it visible
	            	//loginErrorView.setText(error);
	            	//loginErrorView.setVisibility(View.VISIBLE);
	            	toast(error);
	            }
			}
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //hideProgress();
	}
	
	private void getCurrentUser(){
		CustomRequest jsObjRequest = new CustomRequest(
				Method.GET, 
				AppConstant.getUserUrl, 
				null,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	//toast("Response : "+response.toString());
                    	parseJsonAuth(response);
                    	//showProgress(false);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	hideProgress();
                    	toast("Error: " + error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	private void parseJsonAuth(JSONObject response) {
        try {
        	//toast(response.toString());
            if(response.has("success")){
            	String success = response.getString("success");
            	toast(success);
            	User user = User.parseFromJsonObject(response);
            	if(user==null){
            		toast("An error occured");
            		return;
            	}
            	AppConstant.userConnected = user;
            	firstnameEditText.setText(user.getFirstname());
            	lastnameEditText.setText(user.getLastname());
            	middlenameEditText.setText(user.getMiddlename());
            	occupationEditText.setText(user.getOccupation());
            	aboutmeEditText.setText(user.getAboutMe());
            	profileImageView.setImageUrl(user.getPictureUrl(), imageLoader);
            	hideProgress();
            	formScrollView.setVisibility(View.VISIBLE);
            	
            }else if(response.has("error")){
            	String error = response.getString("error");
            	//TODO Show the error message in a textView and make it visible
            	toast(error);
            	hideProgress();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            hideProgress();
        }
    }
	

	public File compress(String originalPath){
		String tempFile = Environment.getExternalStorageDirectory() +"/marker_temp_image.jpg";
		return compress(originalPath, tempFile);
	}
	
	public File compress(String originalPath, String outputPath){
		Bitmap bmp = BitmapFactory.decodeFile(originalPath);
		File file = new File (outputPath);
		//String filePath = file.getAbsolutePath();
		if (file.exists ()) file.delete ();
		try {
			FileOutputStream out = new FileOutputStream(file);
			bmp.compress(Bitmap.CompressFormat.JPEG, 70, out);
		    out.flush();
		    out.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return file.exists()?file:null;
	}
	
	private void upload(){
		/*
		toast("Uploading : "+currentSelectedFile.getAbsolutePath());
		HttpUploader uploader = new HttpUploader(AppConstant.uploadPhotoUrl, currentSelectedFile.getAbsolutePath(),
				new IRefresher<String>() {
					
					@Override
					public boolean refresh(String t) {
						toast("Success : "+t);
						return false;
					}
				},
				new IRefresher<String>() {
					
					@Override
					public boolean refresh(String t) {
						toast("Error : "+t);
						return false;
					}
				}
				);
		
		try {
			uploader.upload();
		} catch (Exception ex) {
			Log.e("Upload", ex==null?"No message":ex.getMessage());
			// TODO Auto-generated catch block
			ex.printStackTrace();
		}
		if(true) return;
		
		*/
		if(currentSelectedFile==null) {
			toast(getResources().getString(R.string.no_image_selected));
			return;
		}
		File temp = compress(currentSelectedFile.getAbsolutePath());
		if(temp==null) {
			toast("Error (file compress) ...");
			return;
		}
		Map<String, String> params = new HashMap<String, String>();
		showProgress();
		UploadRequest jsObjRequest = new UploadRequest(
				AppConstant.uploadPhotoUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	hideProgress();
                    	toast("Response : "+response.toString());
                    	Log.i("Test", response.toString());
                    	parseJsonUpload(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	hideProgress();
                    	toast("Error: " + error.getMessage());
                    	Log.e("Test", error.getMessage());
                    }
                },
                temp/*currentSelectedFile*/
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	private void parseJsonUpload(JSONObject response){
		try {
        	//toast(response.toString());
            if(response.has("success")&&response.has("file")){
            	String success = response.getString("success");
            	toast(success);
            	String file = response.getString("file");
            	if(file!=null&&!file.trim().equals("")){
            		currentUploadeFile = file;
            		toast(getResources().getString(R.string.file_uploaded));
            	}else{
            		toast(getResources().getString(R.string.error_while_uploading));
            	}
            }else if(response.has("error")){
            	String error = response.getString("error");
            	toast(error);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
	}

    private void toast(String text){
		Toast.makeText(this.getActivity(), text, Toast.LENGTH_SHORT).show();
	}
}
